<script setup lang="ts">
import type { CascaderDiff } from '@/components/Cascader'

import { useFullscreen } from '@vueuse/core'

import { getCdnNodeCascadeApi } from '@/apis/modules/cdn'
import { CdnCascader } from '@/components/Cascader'
import ContainerContent from '@/components/ContentContainer.vue'
import CascadeTipsDialog from './components/CascadeTipsDialog.vue'
// import { useAppStore } from '@/stores/app'
import ConfirmDialog from './components/ConfirmDialog.vue'
import EditNodeDialog from './components/EditNodeDialog.vue'
import OperationBar from './components/OperationBar.vue'
// const appStore = computed(() => useAppStore())

const cascadeWrap = ref()
const {
  isFullscreen,
  enter: enterFullscreen,
  exit: exitFullscreen,
} = useFullscreen(cascadeWrap)

const {
  visible: confirmDialogVisible,
  data: confirmDialogRecord,
  open: openConfirmDialog,
} = usePopup()

const {
  visible: editDialogVisible,
  data: editDialogData,
  open: openEditDialog,
} = usePopup()

const { visible: tipsDialogVisible, open: openCascadeTipsDialog } = usePopup()

// const { visible: tipsVideoDialogVisible, open: openTipsVideoDialog }
//   = usePopup()
// onMounted(() => {
//   if (!appStore.value.nodeCascadeVideoTipsShowed) {
//     openTipsVideoDialog()
//   }
// })

const data = ref({ charts: [] })
const { request: getCascadeList } = useRequest(getCdnNodeCascadeApi, {
  success(res) {
    // data.value.charts
    //   = res?.list
    //     ?? [
    //       {
    //         id: '1863766737250422784',
    //         name: '中国大陆中国大陆中国大陆中国大陆中国大陆',
    //         l1_nodes: null,
    //         l2_nodes: null,
    //       },
    //       {
    //         id: '1864122199682584576',
    //         name: '四川成都☝',
    //         l1_nodes: [
    //           {
    //             id: '1934805403359514624',
    //             region_id: '1864122199682584576',
    //             name: '172.16.0.250',
    //             ips: ['172.16.0.250'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //           {
    //             id: '1922892299008741376',
    //             region_id: '1864122199682584576',
    //             name: '18777',
    //             ips: ['172.16.1.13'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //           {
    //             id: '1894628210432282624',
    //             region_id: '1864122199682584576',
    //             name: '172.16.0.189',
    //             ips: ['172.16.0.189'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //         ],
    //         l2_nodes: null,
    //       },
    //       {
    //         id: '1866052107442851840',
    //         name: '不要玩我的原神',
    //         l1_nodes: [
    //           {
    //             id: '1922933450835234816',
    //             region_id: '1866052107442851840',
    //             name: '3.114',
    //             ips: ['192.168.3.114'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //         ],
    //         l2_nodes: [
    //           {
    //             id: '1871015082205384704',
    //             region_id: '1866052107442851840',
    //             name: '192.168.3.105',
    //             ips: ['192.168.3.105'],
    //             status: 1,
    //             resolve_status: 2,
    //           },
    //         ],
    //       },
    //       {
    //         id: '1866307534575374336',
    //         name: '新添加的区域独立版DNS独立版DNS独立',
    //         l1_nodes: [
    //           {
    //             id: '1871016157721399296',
    //             region_id: '1866307534575374336',
    //             name: '192.168.3.104',
    //             ips: ['192.168.3.104'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //         ],
    //         l2_nodes: null,
    //       },
    //       {
    //         id: '1934883900937474048',
    //         name: 'mark区域',
    //         l1_nodes: [
    //           {
    //             id: '1934505833287127040',
    //             region_id: '1934883900937474048',
    //             name: '亚太中国区',
    //             ips: ['172.16.1.6'],
    //             status: 1,
    //             resolve_status: 1,
    //           },
    //         ],
    //         l2_nodes: null,
    //       },
    //     ].map((item) => {
    //       return {
    //         region_id: item.id,
    //         region_name: item.name,
    //         node_L1:
    //         item.l1_nodes?.map(i => ({
    //           node_id: i.id,
    //           node_name: i.name,
    //           region_id: i.region_id,
    //           region_name: item.name,
    //           node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
    //           run_status: i.status,
    //           resolve_status: i?.resolve_status,
    //           level: 1,
    //         })) || [],
    //         node_L2:
    //         item.l2_nodes?.map(i => ({
    //           node_id: i.id,
    //           node_name: i.name,
    //           region_id: i.region_id,
    //           region_name: item.name,
    //           node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
    //           run_status: i.status,
    //           resolve_status: i?.resolve_status,
    //           level: 2,
    //         })) || [],
    //       }
    //     })

    data.value.charts = res?.list?.map((item) => {
      return {
        region_id: item.cluster_info.id,
        region_name: item.cluster_info.name,
        node_L1:
          item.l1_nodes?.map(i => ({
            node_id: i.id,
            node_name: i.name,
            region_id: i.cluster_id,
            region_name: item.cluster_info.name,
            node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
            run_status: i.status,
            resolve_status: i?.resolve_status,
            level: 1,
          })) || [],
        node_L2:
          item.l2_nodes?.map(i => ({
            node_id: i.id,
            node_name: i.name,
            region_id: i.cluster_id,
            region_name: item.cluster_info.name,
            node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
            run_status: i.status,
            resolve_status: i?.resolve_status,
            level: 2,
          })) || [],
      }
    })
  },
})

const cascaderRef = ref<InstanceType<typeof CdnCascader>>()

const diff = ref<CascaderDiff[]>([])
const dataSource = computed(() => {
  return data.value || { charts: [] }
})
const tipsValue = ref({
  error: 0,
  warning: 0,
  risks: [] as string[],
})
provide('tipsValue', tipsValue)

// 编辑节点保存成功
function handleSaveSuccess() {
  getCascadeList()
}

const confirmDialogRef = ref<InstanceType<typeof ConfirmDialog>>()
function handleEditNode(nodeId: string) {
  if (isFullscreen.value)
    return
  if (!diff.value.length) {
    return openEditDialog(nodeId)
  }
  ModalHelper.confirm(
    {
      content: '您的操作尚未保存，确定要进行节点编辑？',
      okText: '保存并编辑',
    },
    async () => {
      await confirmDialogRef.value?.save(diff.value)
      diff.value = []
      // Message.success('操作成功')
      openEditDialog(nodeId)
    },
  )
}

onMounted(getCascadeList)

function handleBeforeUnload(event) {
  if (diff.value.length) {
    event.preventDefault()
    // CloudModal.confirm(
    //   {
    //     content: '您的操作尚未保存，确定要刷新页面？',
    //     okText: '刷新'
    //   },
    //   async () => {
    //     window.location.reload()
    //   }
    // )
  }
}

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
const isShowOperationActionCard = computed(() => {
  const tipDiff = diff.value.filter(item => item.diffType !== 'SORT').length
  return tipDiff === 0
})
// 路由离开前触发
onBeforeRouteLeave((to, from, next) => {
  if (!isShowOperationActionCard.value) {
    ModalHelper.confirm(
      {
        content: '您的操作尚未保存，确定要离开页面？',
        okText: '确定',
      },
      async () => {
        next()
      },
    )
  } else {
    next()
  }
})
</script>

<template>
  <container-content
    :pagination="false"
    :refresh="false"
    class="!h-full !overflow-auto"
    @run="getCascadeList"
  >
    <template #header>
      <div class="text-5 font-700">
        节点级联
        <span
          class="ml-2 cursor-pointer text-xs text-[#00A65B] font-normal"
          @click="() => openCascadeTipsDialog()"
        >节点级联说明</span>
      </div>
    </template>
    <div class="cascade-view">
      <operation-bar
        :error="tipsValue.error"
        :warning="tipsValue.warning"
        :diff="diff"
        @save-config="openConfirmDialog(diff)"
        @fullscreen="enterFullscreen"
        @error-click="cascaderRef?.position('error')"
        @warning-click="cascaderRef?.position('warning')"
      />
      <div
        ref="cascadeWrap"
        class="cascade-wrap"
      >
        <cdn-cascader
          ref="cascaderRef"
          v-model:diff="diff"
          v-model:tips="tipsValue"
          class="relative w-full"
          :data="dataSource || []"
          :is-fullscreen="isFullscreen"
          @node-click="(_, node) => handleEditNode(node.node_id)"
        >
          <template #exit-fullscreen>
            <header
              v-if="isFullscreen"
              class="cdn-cascader__header"
            >
              <span class="text-[16px] font-bold">级联管理</span>
              <div class="flex-1" />
              <span class="exit-fullscreen">
                <a-button @click="exitFullscreen"> 退出全屏 </a-button>
              </span>
            </header>
          </template>
        </cdn-cascader>
      </div>
    </div>
    <confirm-dialog
      ref="confirmDialogRef"
      v-model:visible="confirmDialogVisible"
      v-model:record="confirmDialogRecord"
      :tips="tipsValue.risks"
      :diff-data="cascaderRef?.modelValue!"
      @save="getCascadeList"
    />
    <edit-node-dialog
      v-model:visible="editDialogVisible"
      v-model:record="editDialogData"
      @save="handleSaveSuccess"
    />
    <!-- <tips-video-dialog v-model:visible="tipsVideoDialogVisible" /> -->
    <cascade-tips-dialog v-model:visible="tipsDialogVisible" />
  </container-content>
</template>

<style scoped lang="less">
.cascade-view {
  @apply bg-white h-full rounded-md flex flex-col;
  .cascade-wrap {
    @apply !h-full !overflow-hidden;
  }
}
</style>
